/**
 * Created by rockyren on 14/11/29.
 */

/**
 * 个人资料控制器
 */
personalApp.controller('baseinfoController',['$scope','baseinfoServices', 'errorShowServices', function($scope, baseinfoServices, errorShowServices){

  function loadBaseinfo() {
    baseinfoServices.get()
      .success(function(data){
        $scope.info = data;

        if($scope.info.birthday) {
          var birthdayDate = new Date($scope.info.birthday);
          $scope.birthday = {
            year: birthdayDate.getFullYear(),
            month: birthdayDate.getMonth() + 1,
            day: birthdayDate.getDate()
          };
        }else{
          $scope.birthday = {
            year: null,
            month: null,
            day: null
          }
        }


      })
      .error(function(data){
        console.log(data.error);
      });
  }
  loadBaseinfo();

  /**
   * 保存资料提交
   */
  $scope.submit = function(){
    baseinfoServices.update({
      realname: $scope.info.realname,
      sex: $scope.info.sex,
      birthday: $scope.birthday.year + '-' + $scope.birthday.month + '-' + $scope.birthday.day,
      nickname: $scope.info.nickname
    })
      .success(function(data){
        if(data.status && data.status == 'failure') {
          errorShowServices.alertErrorMessage('保存失败', data.message);
        }else{

          alert('保存成功');
          loadBaseinfo();
        }
      })
      .error(function(data){

      });
  };



  /**
   * 日期管理,获得年,月,日列表
   */
  $scope.dateHandle = (function(){
    var today = new Date();
    var monthList = [1,2,3,4,5,6,7,8,9,10,11,12];
    var yearList = [];
    for(var i = 1930;i <= today.getFullYear();i++){
      yearList.push(i);
    }

    var dayList;


    return {
      //获得年份数组
      getYearList: function(){
        return yearList;
      },
      //获得月份数组
      getMonthList: function(){
        return monthList;
      },
      //根据年和月获得对象的日数组
      getDayList: function(year,month){
        var lastDay;
        dayList = [];

        //取当前年份
        var new_year = year;
        //取下一个月的第一天,减去1天就可以得到当月的最后一天
        var new_month = month++;
        if(month > 12) {
          new_month -= 12;
          new_year++;
        }
        var new_date = new Date(new_year,new_month,1);

        lastDay =  (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();

        //如果birDay比lastDay大,则将其设为lastDay
        if($scope.birthday && $scope.birthday.day > lastDay) {
          $scope.birthday.day = lastDay;
        }


        for(var i = 1;i <= lastDay; i++){
          dayList.push(i);
        }
        return dayList;
      }


    }
  })();


}]);